package com.vivz.baby.service.http;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.vivz.baby.dao.LogDAO;
import com.vivz.baby.domain.Log;

/**
 * Http User Service Implementation
 * 
 * @author Vivek More
 * @since 10 Mar 2012
 * @version 1.0.0
 *
 */
public class HttpLogService implements IHttpLogService {

    private static Logger logger = Logger.getLogger(HttpLogService.class);

    // Remote Cache Service is injected...
    @Autowired
    private final LogDAO logDAO;

    public boolean log(Log data) {
	try {
	    logDAO.save(data);
	} catch (Exception e) {
	    logger.error(e);
	    return false;
	}
	return true;
    }

    public HttpLogService(final LogDAO logDAO) {
	this.logDAO = logDAO;
    }

    public List<Log> getTodaysLogs(Long userId) {
	Calendar c = Calendar.getInstance();
	Date now = c.getTime();
	c.set(Calendar.HOUR, c.getActualMinimum(Calendar.HOUR));
	c.set(Calendar.MINUTE, c.getActualMinimum(Calendar.MINUTE));
	c.set(Calendar.SECOND, c.getActualMinimum(Calendar.SECOND));
	Date todayMidnight = c.getTime();
	return logDAO.findByUserIdAndLogTimeBetween(userId, todayMidnight, now);
    }

    public List<Log> getThisMonthsLogs(Long userId) {

	Calendar c = Calendar.getInstance();
	c.set(Calendar.HOUR, c.getActualMinimum(Calendar.HOUR));
	c.set(Calendar.MINUTE, c.getActualMinimum(Calendar.MINUTE));
	c.set(Calendar.SECOND, c.getActualMinimum(Calendar.SECOND));
	Date d1 = c.getTime();
	c.set(Calendar.DATE, c.getActualMinimum(Calendar.DATE));
	Date d2 = c.getTime();
	return logDAO.findByUserIdAndLogTimeBetween(userId, d1, d2);
    }

    public List<Log> getThisYearsLogs(Long userId) {

	Calendar c = Calendar.getInstance();
	c.set(Calendar.HOUR, c.getActualMinimum(Calendar.HOUR));
	c.set(Calendar.MINUTE, c.getActualMinimum(Calendar.MINUTE));
	c.set(Calendar.SECOND, c.getActualMinimum(Calendar.SECOND));
	Date d1 = c.getTime();
	c.set(Calendar.DATE, c.getActualMinimum(Calendar.DATE));
	c.set(Calendar.MONTH, c.getActualMinimum(Calendar.MONTH));
	Date d2 = c.getTime();
	return logDAO.findByUserIdAndLogTimeBetween(userId, d1, d2);
    }

}
